package com.atguigu.servlet;

import com.atguigu.domain.User;
import com.atguigu.service.UserService;
import com.atguigu.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author dl
 * @create 2020-04-18-16:13
 */
@WebServlet(name = "RegisterServlet",urlPatterns = "/user/register")
public class RegisterServlet extends BaseServlet {

	private UserService userService = new UserServiceImpl();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	protected void existsName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		String email = req.getParameter("email");

		boolean flag = userService.userRegister(new User(null, username, password, email));
		if (flag) {
			// register success to the regist_success.jsp
			resp.sendRedirect(req.getContextPath() + "/pages/user/regist_success.jsp");
		}else {
			// forward to the regist.jsp and show register failed
			req.setAttribute("msg","用户名已存在");
			req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
		}
	}

	protected void existsNameAjax(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		String email = req.getParameter("email");

		boolean flag = userService.userRegister(new User(null, username, password, email));
		if (flag) {
			// register success to the regist_success.jsp
			resp.sendRedirect(req.getContextPath() + "/pages/user/regist_success.jsp");
		}else {
			// forward to the regist.jsp and show register failed
			req.setAttribute("msg","用户名已存在");
			req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
		}
	}
}
